package com.eqxiu.ieditor.api.impl;

import com.eqxiu.ieditor.api.HomePageUserServiceApi;
import com.eqxiu.ieditor.dao.HomePageUserMapper;
import com.eqxiu.ieditor.dao.HomePageUserSceneMapper;
import com.eqxiu.ieditor.dto.HomePageUserDTO;
import com.eqxiu.ieditor.dto.HomePageUserParam;
import com.eqxiu.ieditor.dto.HomePageUserSceneDTO;
import com.eqxiu.ieditor.entity.HomePageUser;
import com.eqxiu.ieditor.entity.HomePageUserCriteria;
import com.eqxiu.ieditor.entity.HomePageUserScene;
import com.eqxiu.scene.api.SceneServiceApi;
import com.eqxiu.scene.dto.SceneDTO;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.ibatis.annotations.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.security.Key;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName HomePageUserServiceApiImpl
 * @escription TODO
 * @Author suixiangyu
 * @Date 2019/4/39:52 AM
 */
@Service
public class HomePageUserServiceApiImpl implements HomePageUserServiceApi {

    private final Logger LOGGER = LoggerFactory.getLogger(HomePageUserServiceApiImpl.class);

    @Autowired
    private HomePageUserMapper homePageUserMapper;

    @Autowired
    private HomePageUserSceneMapper homePageUserSceneMapper;

    @Autowired
    private UserApi userApi;


    @Autowired
    private SceneServiceApi sceneServiceApi;

    @Override
    public void addHomePageUserMessage(HomePageUserDTO homePageUserDTO) {
        HomePageUser homePageUser = new HomePageUser();
        BeanUtils.copyProperties(homePageUserDTO, homePageUser);
        homePageUserMapper.insert(homePageUser);
    }

    @Override
    public HomePageUserDTO queryHomePageUserMessage(String userId) {
        HomePageUserCriteria homePageUserCriteria = new HomePageUserCriteria();
        homePageUserCriteria.createCriteria().andUserIdEqualTo(userId);
        List<HomePageUser> homePageUsers = homePageUserMapper.selectByExample(homePageUserCriteria);
        if (homePageUsers != null && homePageUsers.size() > 0) {
            HomePageUserDTO backHomePageUserDTO = new HomePageUserDTO();
            BeanUtils.copyProperties(homePageUsers.get(0), backHomePageUserDTO);
            return backHomePageUserDTO;
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Object> queryHomePageByParms(Map<String, Object> params) {
        int pageNumber = (Integer) params.get("pageNumber");
        int pageSize = (Integer) params.get("pageSize");
        //modify by suixiangyu 修改查询slow sql
        //PageHelper.startPage(pageNumber, pageSize);
        Map<String, Object> map = Maps.newHashMap();
        params.put("pageSize",pageSize);
        params.put("curPage",(pageNumber-1)*pageSize);
        List<Map<String, Object>> list = homePageUserMapper.selectHomePageUserByParams(params);
        int count = homePageUserMapper.selectHomePageUserCountByParams(params);
        //PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        map.put("total", count);
        map.put("rows", list);
        return map;
    }

    @Override
    public void addHomePageUserAndSceneForEditor(String userId, String sceneId) {
        LOGGER.info("===addHomePageUserAndSceneForEditor begin==="+userId+"sceneId"+sceneId);
        /**
         *处理微主页用户信息
         **/
        HomePageUser homePageUser = new HomePageUser();
        //获取用户基础信息
        User baseUser = userApi.getUser(userId);
        //判断微主页用户是否存在
        HomePageUserDTO checkHomePageUser = this.queryHomePageUserMessage(userId);
        if (checkHomePageUser == null) {
            if (baseUser != null){
                homePageUser.setUserId(userId);
                homePageUser.setPhone(baseUser.getPhone());
                homePageUser.setLoginId(baseUser.getLoginName());
                homePageUser.setLoginTime(new Date());
                homePageUser.setUpdateTime(new Date());
                homePageUser.setNickName(baseUser.getNick());
                //保存微主页用户
                homePageUserMapper.insert(homePageUser);
                LOGGER.info("===保存微主页用户信息success===");
            }
        }
        /**
         *处理作品信息
         **/
        //获取场景基础信息
        SceneDTO scene = sceneServiceApi.getScene(Long.valueOf(sceneId));
        if (scene != null) {
            HomePageUserScene homePageUserScene = new HomePageUserScene();
            homePageUserScene.setUserId(userId);
            homePageUserScene.setSceneName(scene.getName());
            homePageUserScene.setSceneCode(scene.getCode());
            homePageUserScene.setSceneId(Integer.parseInt(String.valueOf(sceneId)));
            homePageUserScene.setCreateTime(new Date());
            homePageUserScene.setUpdateTime(new Date());
            homePageUserScene.setProperty(scene.getProperty());
            homePageUserScene.setImgStr(scene.getCover());
            homePageUserScene.setSort(1000);
            homePageUserScene.setType(2);
            homePageUserScene.setPlatform(1);
            //保存微主页作品
            homePageUserSceneMapper.insert(homePageUserScene);
            LOGGER.info("===保存微主页作品信息success===");
        }

    }


    /**
     * 根据条件查询微主页的用户信息管理----max后台使用-----优化后
     * 当选择 开始微主页作品数排序后  前面用户登录名等筛选都失效，
     * 将以前的left join改成根据各种条件单表查询
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> findHomePageByParams(HomePageUserParam params) {
        LOGGER.info("开始查询了----");
        Long start = System.currentTimeMillis();
        int pageNumber = params.getPageNumber();
        int pageSize = params.getPageSize();
        Map<String, Object> returnMap = Maps.newHashMap();
        params.setCurPage((pageNumber - 1) * pageSize);
        if (params.getOrderByProperty() != null && !params.getOrderByProperty().equals("openPageCount")) {
            LOGGER.info("非作品数量查询");
            Long startOne = System.currentTimeMillis();
            LOGGER.info("非作品数量查询开始分页----" + startOne);
            List<HomePageUserDTO> list = homePageUserMapper.queryHomePageUserByParams(params);
            Long endOne = System.currentTimeMillis();
            LOGGER.info("非作品数量查询结束分页----" + endOne);
            LOGGER.info("非作品数量查询时间差----" + (endOne - startOne));
            if (!CollectionUtils.isEmpty(list)) {
                List<String> userIds = Lists.newArrayList();
                for (HomePageUserDTO dto : list) {
                    if (dto.getUserId() != null) {
                        userIds.add(dto.getUserId());
                    }
                }
                Long startTwo = System.currentTimeMillis();
                List<HomePageUserDTO> countList = homePageUserMapper.queryCountByUserIds(userIds);
                Long endTwo = System.currentTimeMillis();
                LOGGER.info("查询作品数" + (endTwo - startTwo));
                if (!CollectionUtils.isEmpty(countList)) {
                    Map<String, HomePageUserDTO> pageUserCountMap = countList.stream().collect(Collectors.toMap(HomePageUserDTO::getUserId, Function.identity(), (key1, key2) -> key2));
                    for (HomePageUserDTO dto : list) {
                        if (pageUserCountMap.get(dto.getUserId()) != null) {
                            dto.setOpenPageCount(pageUserCountMap.get(dto.getUserId()).getOpenPageCount());
                        }
                    }
                }
            }
            Long startThree = System.currentTimeMillis();
            LOGGER.info("count开始" + startThree);
            int count = homePageUserMapper.queryCountHomePage(params);
            Long endThree = System.currentTimeMillis();
            LOGGER.info("count结束" + (endThree - startThree));
            returnMap.put("rows", list);
            returnMap.put("total", count);
        } else {
            LOGGER.info("作品数量查询");
            Long startOne = System.currentTimeMillis();
            LOGGER.info("作品数量查询开始分页----" + startOne);
            List<HomePageUserDTO> list = homePageUserSceneMapper.queryHomePageSceneByParams(params);
            Long endOne = System.currentTimeMillis();
            LOGGER.info("作品数量查询结束分页----" + endOne);
            LOGGER.info("作品数量查询时间差----" + (endOne - startOne));
            List<HomePageUserDTO> homePageUserDTOS = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(list)) {
                Map<String, HomePageUserDTO> pageUserCountMap = list.stream().collect(Collectors.toMap(HomePageUserDTO::getUserId, Function.identity(), (key1, key2) -> key2));
                List<String> userIds = Lists.newArrayList();
                for (String userId : pageUserCountMap.keySet()) {
                    userIds.add(userId);
                }
                homePageUserDTOS = homePageUserMapper.queryHomePageByUserIds(userIds);
                for (HomePageUserDTO dto : homePageUserDTOS) {
                    String userId = dto.getUserId();
                    if (pageUserCountMap.get(userId) != null) {
                        dto.setOpenPageCount(pageUserCountMap.get(userId).getOpenPageCount());
                    }
                }
            }
            if (params.getOrderByClause().equalsIgnoreCase("desc")) {
                homePageUserDTOS.sort(Comparator.comparing(HomePageUserDTO::getOpenPageCount).reversed());
            } else {
                homePageUserDTOS.sort(Comparator.comparing(HomePageUserDTO::getOpenPageCount));
            }
            returnMap.put("rows", homePageUserDTOS);
            LOGGER.info("count------------");
            Long startTwo = System.currentTimeMillis();
            int count = homePageUserSceneMapper.queryCountHomePageScene(params);
            Long endTwo = System.currentTimeMillis();
            LOGGER.info("count----" + (endTwo - startTwo));
            returnMap.put("total", count);
        }
        LOGGER.info("结束查询----");
        Long end = System.currentTimeMillis();
        LOGGER.info("整体时间差----" + (end - start));
        return returnMap;
    }
}
